//
//  ViewController.m
//  ChargeHelper
//
//  Created by Coby on 17/9/6.
//  Copyright © 2017年 梦拓科技. All rights reserved.
//

#import "ViewController.h"
#import "TaskWallSystem.h"
#import "RechargeMainTableViewController.h"
#import "CommitTaskController.h"
#import "Common.h"

@interface ViewController ()
@property (nonatomic, weak) IBOutlet UIToolbar *toolbar;
//Labels
@property (nonatomic, weak) IBOutlet UILabel * StateInfoLabe;
@property (nonatomic, weak) IBOutlet UILabel * TaskNameInfo;
@property (nonatomic, weak) IBOutlet UILabel * TaskBundleInfo;
@property (nonatomic, weak) IBOutlet UILabel * TaskPlayTime;
@property (nonatomic, weak) IBOutlet UILabel * AreaLabel;
@property (nonatomic, weak) IBOutlet UILabel * CurrentAreaLabel;
@property (nonatomic, weak) IBOutlet UILabel * OriginalLevel;
@property (nonatomic, weak) IBOutlet UILabel * ExpectedLevel;
//Button
@property (nonatomic, weak) IBOutlet UIButton * AccountNameBtn;
@property (nonatomic, weak) IBOutlet UIButton * AccountPassBtn;
@property (nonatomic, weak) IBOutlet UIButton * CardIDBtn;
@property (nonatomic, weak) IBOutlet UIButton * UserNameBtn;
@property (nonatomic, weak) IBOutlet UIButton * HadPhoneNumBtn;
@property (nonatomic, weak) IBOutlet UIButton * PhoneNumBtn;
@property (nonatomic, weak) IBOutlet UIButton * VerCodeBtn;
@property (nonatomic, weak) IBOutlet UIButton * GetOrFreedBtn;
@property (nonatomic, weak) IBOutlet UIButton * GetAreaBtn;
@property (nonatomic, weak) IBOutlet UIButton * SwitchAccountBtn;

@property (nonatomic, weak) IBOutlet UIButton * TaskStartBtn;
@property (nonatomic, weak) IBOutlet UIButton * TaskStopBtn;
@property (nonatomic, weak) IBOutlet UIButton * TaskCommitBtn;

@property (nonatomic, weak) IBOutlet UILabel * ControllerLog;//日志控制台
@property (nonatomic,strong) NSMutableArray * LogArray;

@property (nonatomic, strong) NSTimer *myTime;


@end

@implementation ViewController

- (void)viewDidLoad {
    _ControllerLog.numberOfLines=0;
    if(_LogArray==nil){
        NSLog(@"LogArrayInit");
        _LogArray=[NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"",@"",@"",@"",@"",@"", nil];
    }
    
    [super viewDidLoad];
    
    
    self.GetOrFreedBtn.tag = 999;
    [self.PhoneNumBtn setTitle:@"" forState:UIControlStateNormal];
    [self.VerCodeBtn setTitle:@"" forState:UIControlStateNormal];
    
    [self backTaskResume];
//    [self refreshUIView];
    [self configureToolbar];
    
    
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss +SSSS"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    
    [self LogStr:[NSString stringWithFormat:@"等级助手初始化完成%@", dateString]];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self refreshUIView];
    NSLog(@"viewWillAppear");
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSFileManager * fileManger = [NSFileManager defaultManager];
    if([fileManger fileExistsAtPath:UserSettingFile isDirectory:false]==true){
        NSMutableDictionary * tempMutableDictionary=[NSMutableDictionary dictionaryWithContentsOfFile:UserSettingFile];
        if (tempMutableDictionary[@"userID"]){
            NSString *userId =tempMutableDictionary[@"userID"];
            [TaskWallSystem sharedInstance].userId=userId;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    
    if (self.myTime) {
        [self.myTime invalidate];
        self.myTime = nil;
    }
}


+(ViewController *)getViewController{
    return (ViewController *)self;
}
//设备缓存还原
-(void) backTaskResume{
    NSFileManager * fileManger = [NSFileManager defaultManager];
    if([[TaskWallSystem sharedInstance] SelectedTaskFromList]==nil||[fileManger fileExistsAtPath:SelectedTaskFile isDirectory:false]==true){
        [[TaskWallSystem sharedInstance] setSelectedTaskFromList:[NSMutableDictionary dictionaryWithContentsOfFile:SelectedTaskFile]];
        [self LogStr:@"从缓存中恢复选中任务"];
    }
    if([[TaskWallSystem sharedInstance] ChargeTaskList]==nil||[fileManger fileExistsAtPath:TaskFile isDirectory:false]==true){
        [[TaskWallSystem sharedInstance] setChargeTaskList:[NSMutableDictionary dictionaryWithContentsOfFile:TaskFile]];
        if([[[TaskWallSystem sharedInstance] ChargeTaskList][@"code"] integerValue]!=1){
            [self removeTaskChace];
            return;
        }
        [self LogStr:[NSString stringWithFormat:@"code:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"code"]]];
        [self LogStr:[NSString stringWithFormat:@"message:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"message"]]];
        if([[TaskWallSystem sharedInstance] ChargeTaskList][@"ChargeHelperState"])
        {
            if([[[TaskWallSystem sharedInstance] ChargeTaskList][@"ChargeHelperState"] integerValue]==0){
                [[TaskWallSystem sharedInstance] setRechargetQuestState:ChargeNull];
            }else if([[[TaskWallSystem sharedInstance] ChargeTaskList][@"ChargeHelperState"] integerValue]==1){
                [[TaskWallSystem sharedInstance] setRechargetQuestState:chareWaitInit];
            }else if([[[TaskWallSystem sharedInstance] ChargeTaskList][@"ChargeHelperState"] integerValue]==2){
                [[TaskWallSystem sharedInstance] setRechargetQuestState:ChargeWaitInput];
            }else if([[[TaskWallSystem sharedInstance] ChargeTaskList][@"ChargeHelperState"] integerValue]==3){
                [[TaskWallSystem sharedInstance] setRechargetQuestState:ChargeWaitRequest];
            }
        }
        [self LogStr:@"从缓存中恢复当前任务"];
    }
}

-(void)removeSelectedTaskChace{
    NSFileManager * fileManger = [NSFileManager defaultManager];
    if([fileManger fileExistsAtPath:SelectedTaskFile isDirectory:false]==true){
        [fileManger removeItemAtPath:SelectedTaskFile error:nil];
        [self LogStr:@"清除选中任务缓存"];
    }
}

-(void)removeTaskChace{
    NSFileManager * fileManger = [NSFileManager defaultManager];
    if([fileManger fileExistsAtPath:TaskFile isDirectory:false]==true){
        [fileManger removeItemAtPath:TaskFile error:nil];
        [self LogStr:@"清除当前进行的任务缓存"];
    }
}

-(void)configureToolbar{
    NSArray *toolbarButtonItems = @[[self trashBarButtonItem], [self flexibleSpaceBarButtonItem], [self customTitleBarButtonItem]];
    [self.toolbar setItems:toolbarButtonItems animated:YES];
}
#pragma mark - UIBarButtonItem Creation and Configuration
- (UIBarButtonItem *)trashBarButtonItem {
    return [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(trashBarItemClicked:)];
}

- (UIBarButtonItem *)flexibleSpaceBarButtonItem {
    return [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
}

- (UIBarButtonItem *)customTitleBarButtonItem {
    NSString *customTitle = NSLocalizedString(@"任务列表", nil);
    return [[UIBarButtonItem alloc] initWithTitle:customTitle style:UIBarButtonItemStylePlain target:self action:@selector(barButtonItemClicked:)];
}

#pragma mark - Actions
//任务列表
- (void)barButtonItemClicked:(UIBarButtonItem *)barButtonItem {
    NSLog(@"[[TaskWallSystem sharedInstance] userId] = %@",[[TaskWallSystem sharedInstance] userId]);
    if ([[TaskWallSystem sharedInstance] userId]==nil) {
        [self LogStr:@"没有设置用户，请在右上角进行设置"];
    }else{
        NSLog(@"A bar button item on the default toolbar was clicked: %@.", barButtonItem);
        RechargeMainTableViewController *controller=[[RechargeMainTableViewController alloc] initWithNibName:@"RechargeMainTableViewController" bundle:nil];
        [self.navigationController pushViewController:controller animated:TRUE];
    }
}
//删除选择任务
- (void)trashBarItemClicked:(UIBarButtonItem *)barButtonItem {
    NSLog(@"Trash Item Cicked");
    if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeNull )
    {
        [[TaskWallSystem sharedInstance] setSelectedTaskFromList:nil];
        [self LogStr:@"移除当前选择的任务"];
        [self removeSelectedTaskChace];
        [self refreshUIView];
    }else{
        [self LogStr:@"请先停止任务"];
    }
}
//刷新UI
-(void)refreshUIView{
    NSLog(@"refreshUIView");
    [self refreshUIBtnView];
    [self refreshTaskInfoLableUI];
}

//刷新UI Button
-(void)refreshUIBtnView{
    NSLog(@"refreshUIBtnView");
    
    if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeNull){
        [_TaskStartBtn setEnabled:YES];
        [_TaskStartBtn setTitle: @"开始任务" forState: UIControlStateNormal];
        [_TaskStopBtn setEnabled:NO];
        [_TaskCommitBtn setEnabled:NO];
    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==chareWaitInit){
        [_TaskStartBtn setTitle: @"刷新初始化状态" forState: UIControlStateNormal];
        
        [_TaskStopBtn setEnabled:YES];
        [_TaskCommitBtn setEnabled:NO];
    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeWaitInput){
        [_TaskCommitBtn setEnabled:YES];

    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeWaitRequest){
        [_TaskStartBtn setEnabled:YES];
        [_TaskCommitBtn setEnabled:NO];
        [_TaskStartBtn setTitle: @"刷新备份状态" forState: UIControlStateNormal];
    }
    else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeFinaRequst){
        [_TaskStartBtn setEnabled:YES];
        [_TaskCommitBtn setEnabled:YES];
        [_TaskStartBtn setTitle: @"上报任务成功" forState: UIControlStateNormal];
        [_TaskCommitBtn setTitle: @"修改数据" forState: UIControlStateNormal];
    }
}

-(void)LogStr:(NSString *)Logstr{
    if(Logstr){
        OOLog(@"加入%@",Logstr);
        [_LogArray removeLastObject];
        [_LogArray insertObject:Logstr atIndex:0];
        _ControllerLog.text=[self getLogControllerString];
    }
}

-(NSString *)getLogControllerString{
    NSString * logStr=@"";
    for( int i=0; i<_LogArray.count; i++){
        NSLog(@"%@",[NSString stringWithFormat:@"%@",[_LogArray objectAtIndex:i]]);
        if(i==_LogArray.count){
            logStr=[logStr stringByAppendingString:[NSString stringWithFormat:@"%@",[_LogArray objectAtIndex:i]]];
            NSLog(@"%@",[NSString stringWithFormat:@"%@",[_LogArray objectAtIndex:i]]);
        }else{
            logStr=[logStr stringByAppendingString:[NSString stringWithFormat:@"%@\n",[_LogArray objectAtIndex:i]]];
            NSLog(@"%@",[NSString stringWithFormat:@"%@\n",[_LogArray objectAtIndex:i]]);
        }
    }
    NSLog(@"finastr:%@",logStr);
    return logStr;
}
//刷新任务UI LABLE
-(void)refreshTaskInfoLableUI{
    NSString *typeStr = @"";
    NSMutableDictionary *TaskDictionary = [[TaskWallSystem sharedInstance] SelectedTaskFromList];
    
    if ([TaskDictionary[@"ServiceTaskType"] intValue] == 1) {
        typeStr = @"新增";
    }
    
    if ([TaskDictionary[@"ServiceTaskType"] intValue] == 2) {
        typeStr = @"留存";
    }
    
    if ([TaskDictionary[@"ServiceTaskType"] intValue] == 4) {
        typeStr = @"新增重做";
    }
    
    if ([TaskDictionary[@"ServiceTaskType"] intValue] == 5) {
        typeStr = @"留存重做";
    }
    
    if ([TaskDictionary[@"ServiceTaskType"] intValue] == 6) {
        typeStr = @"新增练级";
    }
    
    if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeNull)
    {
        _StateInfoLabe.text=[NSString stringWithFormat:@"%@     没有任务进行",typeStr];
    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==chareWaitInit){
//        _StateInfoLabe.text=@"等待初始化";
        _StateInfoLabe.text=[NSString stringWithFormat:@"%@     等待初始化",typeStr];
    }
    else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeWaitInput){
//        _StateInfoLabe.text=@"等待用户手工操作";
        _StateInfoLabe.text=[NSString stringWithFormat:@"%@     等待用户手工操作",typeStr];
        [_TaskStartBtn setTitle: @"" forState: UIControlStateNormal];

    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeWaitRequest){
//        _StateInfoLabe.text=@"等待上报结果并备份";
        _StateInfoLabe.text=[NSString stringWithFormat:@"%@      等待上报结果并备份",typeStr];
    }
    else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeFinaRequst){
//        _StateInfoLabe.text=@"等待上报任务完成";
        _StateInfoLabe.text=[NSString stringWithFormat:@"%@     等待上报任务完成",typeStr];
    }
    
    if([[TaskWallSystem sharedInstance] SelectedTaskFromList]!=nil){
        _TaskNameInfo.text=[NSString stringWithFormat:@"%@",[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"GameInfo"][@"GameName"]];//任务名称
        _TaskBundleInfo.text=[NSString stringWithFormat:@"%@",[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"GameInfo"][@"GameBundleId"]];//BundleID
        
        _TaskPlayTime.text=@"";
        _OriginalLevel.text = @"";
        _ExpectedLevel.text = @"";
        
        [_AccountNameBtn setTitle:@"" forState: UIControlStateNormal];
        [_AccountPassBtn setTitle:@"" forState: UIControlStateNormal];
        [_CardIDBtn setTitle:@"" forState: UIControlStateNormal];
        [_UserNameBtn setTitle:@"" forState:UIControlStateNormal];
        [_HadPhoneNumBtn setTitle:@"" forState: UIControlStateNormal];
        
    }else{
        _TaskNameInfo.text=@"";
        _TaskBundleInfo.text=@"";
        _TaskPlayTime.text=@"";
        _OriginalLevel.text = @"";
        _ExpectedLevel.text = @"";
        
        [_AccountNameBtn setTitle:@"" forState: UIControlStateNormal];
        [_AccountPassBtn setTitle:@"" forState: UIControlStateNormal];
        [_CardIDBtn setTitle:@"" forState: UIControlStateNormal];
        [_UserNameBtn setTitle:@"" forState:UIControlStateNormal];
        [_HadPhoneNumBtn setTitle:@"" forState: UIControlStateNormal];
    }
    
    NSString *codeStr = [[TaskWallSystem sharedInstance] ChargeTaskList][@"code"];
    
    NSLog(@"[[TaskWallSystem sharedInstance] ChargeTaskList] = %@",[[TaskWallSystem sharedInstance] ChargeTaskList]);
    
    if ([[TaskWallSystem sharedInstance] ChargeTaskList] != nil && [codeStr intValue] == 1) {
        _TaskNameInfo.text=[NSString stringWithFormat:@"%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"GameInfo"][@"GameName"]];//任务名称
        _TaskBundleInfo.text=[NSString stringWithFormat:@"%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"GameInfo"][@"GameBundleId"]];//BundleID
        _TaskPlayTime.text=[NSString stringWithFormat:@"最低试玩时间 %@s",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Min_play_time"]];
        _AreaLabel.text = [NSString stringWithFormat:@"%@   %@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Province"],[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"City"]];
        _CurrentAreaLabel.text = [NSString stringWithFormat:@"%@   %@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Province"],[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"City"]];
        
        _OriginalLevel.text = [NSString stringWithFormat:@"%@级",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"StartLeval"]];
        _ExpectedLevel.text = [NSString stringWithFormat:@"%@级",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Leval"]];
        
        
        [_AccountNameBtn setTitle:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountName"] forState: UIControlStateNormal];
        [_AccountPassBtn setTitle:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountPasswd"] forState: UIControlStateNormal];
        [_CardIDBtn setTitle:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountIDcard"] forState: UIControlStateNormal];
        [_UserNameBtn setTitle:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountFullName"] forState:UIControlStateNormal];
        [_HadPhoneNumBtn setTitle:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"] forState: UIControlStateNormal];
        
        [_PhoneNumBtn setTitle:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"] forState:UIControlStateNormal];
        [_VerCodeBtn setTitle:[[TaskWallSystem sharedInstance] ChargeTaskList][@"VerCode"] forState:UIControlStateNormal];
        
    }else {
        
        [_AccountNameBtn setTitle:@"" forState: UIControlStateNormal];
        [_AccountPassBtn setTitle:@"" forState: UIControlStateNormal];
        [_CardIDBtn setTitle:@"" forState: UIControlStateNormal];
        [_UserNameBtn setTitle:@"" forState:UIControlStateNormal];
        [_HadPhoneNumBtn setTitle:@"" forState: UIControlStateNormal];
        [_PhoneNumBtn setTitle:@"" forState:UIControlStateNormal];
        [_VerCodeBtn setTitle:@"" forState:UIControlStateNormal];
    }
    
}
-(IBAction)CopyAccountName:(id)sender{
    if([[TaskWallSystem sharedInstance] ChargeTaskList]!=nil){
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        
        pasteboard.string = [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountName"];
        [self LogStr:[NSString stringWithFormat:@"复制账号到剪贴板:%@", [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountName"]]];
    }else{
        
    }

}
-(IBAction)CopyAccountPass:(id)sender{
    if([[TaskWallSystem sharedInstance] ChargeTaskList]!=nil ){
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountPasswd"];
        [self LogStr:[NSString stringWithFormat:@"复制密码到剪贴板:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountPasswd"]]];
    }else{
        
    }
}

- (IBAction)CopyCardID:(id)sender {
    if([[TaskWallSystem sharedInstance] ChargeTaskList]!=nil){
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountIDcard"];
        [self LogStr:[NSString stringWithFormat:@"复制身份证号码到剪贴板:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountIDcard"]]];
    }else{

    }
}

- (IBAction)CopyUserName:(id)sender {
    if([[TaskWallSystem sharedInstance] ChargeTaskList]!=nil && [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountFullName"] != nil){
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountFullName"];
        [self LogStr:[NSString stringWithFormat:@"复制姓名到剪贴板:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"AccountFullName"]]];
    }else{
        
    }
}


- (IBAction)CopyHadPhoneNum:(id)sender {
    
    NSLog(@"CopyHadPhoneNum:");
    if([[TaskWallSystem sharedInstance] ChargeTaskList] != nil){
        
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"];
        [self LogStr:[NSString stringWithFormat:@"复制手机号码到剪贴板:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"]]];
    }else{

    }
}

- (IBAction)CopyPhoneNum:(id)sender {
    
    NSLog(@"CopyPhoneNum:");
    if([[TaskWallSystem sharedInstance] ChargeTaskList] != nil){
        
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"];
        [self LogStr:[NSString stringWithFormat:@"复制手机号码到剪贴板:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"]]];
    }else{
        
    }
}

- (IBAction)CopyVerCode:(id)sender {
    
    NSLog(@"CopyPhoneNum:");
    if([[TaskWallSystem sharedInstance] ChargeTaskList][@"VerCode"] !=nil ){
        
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [[TaskWallSystem sharedInstance] ChargeTaskList][@"VerCode"];
        [self LogStr:[NSString stringWithFormat:@"复制手机号码到剪贴板:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"VerCode"]]];
    }else{
        
    }
}

- (IBAction)GetOrFreedWithPhoneNumber:(UIButton *)btn {
    
    __weak ViewController *weakSelf = self;
    if (btn.tag == 999) {
        
        if ([[TaskWallSystem sharedInstance] ChargeTaskList] != nil && [[TaskWallSystem sharedInstance] ChargeTaskList][@"VerCode"] != nil) {
            
            NSMutableDictionary *changeDic = [NSMutableDictionary dictionaryWithDictionary:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"]];
            [changeDic setObject:@"" forKey:@"Phone"];
            [[[TaskWallSystem sharedInstance] ChargeTaskList] setObject:@"" forKey:@"VerCode"];
            
            [[[TaskWallSystem sharedInstance] ChargeTaskList] setObject:changeDic forKey:@"data"];
            
            [[[TaskWallSystem sharedInstance] ChargeTaskList] writeToFile:TaskFile  atomically:NO];
            
            [self refreshUIView];
        }
        
        
        if ([[TaskWallSystem sharedInstance] ChargeTaskList] != nil) {
            
            NSDictionary *params = @{
                                     @"userId":[[TaskWallSystem sharedInstance] userId],
                                     @"service_id":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"ServiceId"],
                                     @"taskId":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"TaskId"]
                                     };
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [[TaskWallSystem sharedInstance] requestUseGetWithParam:params requestURL:@"/gettelnum" succeededBlock:^(id responseObject) {
                    
                    __strong ViewController *strongSelf = weakSelf;
                    
                    [strongSelf LogStr:[NSString stringWithFormat:@"获取手机号码， code：%@", responseObject[@"code"]]];
                    [strongSelf LogStr:[NSString stringWithFormat:@"获取手机号码， message：%@", responseObject[@"message"]]];
                    
                    if ([responseObject[@"code"] intValue] == 0) {
                        btn.tag = 1000;
                        [btn setTitle:@"释放" forState:UIControlStateNormal];
                        
                        NSMutableDictionary *changeDic = [NSMutableDictionary dictionaryWithDictionary:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"]];
                        [changeDic setObject:responseObject[@"data"][@"Telnum"] forKey:@"Phone"];
                        
                        [[[TaskWallSystem sharedInstance] ChargeTaskList] setObject:changeDic forKey:@"data"];
                        
                        [[[TaskWallSystem sharedInstance] ChargeTaskList] writeToFile:TaskFile  atomically:NO];
                        
                        [strongSelf refreshUIView];
                        
                        strongSelf.myTime = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(getVerificationCode) userInfo:nil repeats:YES];
                        [[NSRunLoop currentRunLoop] addTimer:strongSelf.myTime forMode:NSRunLoopCommonModes];
                    }
                } errorBlock:^(NSError *error) {
                    
                    __strong ViewController *strongSelf = weakSelf;
                    [strongSelf LogStr:[NSString stringWithFormat:@"获取手机号码失败！"]];
                }];
            });
        }else {
            
            NSLog(@"---------");
        }
        
    }else {
        if ([[TaskWallSystem sharedInstance] ChargeTaskList] != nil) {
            
            NSDictionary *params = @{
                                     @"userId":[[TaskWallSystem sharedInstance] userId],
                                     @"service_id":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"ServiceId"],
                                     @"telnum":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"]
                                     };
            
            [[TaskWallSystem sharedInstance] baseRequestWithParam:params requestURL:@"/freeTelnum" succeededBlock:^(id responseObject) {
                
                __strong ViewController *strongSelf = weakSelf;
                [strongSelf LogStr:[NSString stringWithFormat:@"释放手机号码， code：%@", responseObject[@"code"]]];
                [strongSelf LogStr:[NSString stringWithFormat:@"释放手机号码， message：%@", responseObject[@"message"]]];
                
                btn.tag = 999;
                [btn setTitle:@"获取" forState:UIControlStateNormal];
                
            } errorBlock:^(NSError *error) {
                
                __strong ViewController *strongSelf = weakSelf;
                [strongSelf LogStr:[NSString stringWithFormat:@"获取手机号码失败，请重试！"]];
            }];
            
        }
    }
    
}

- (IBAction)GetAreaBtnWithIBAction:(UIButton *)btn {
    NSMutableDictionary *TaskDictionary = [[TaskWallSystem sharedInstance] SelectedTaskFromList];
    
    NSLog(@"[[TaskWallSystem sharedInstance] ChargeTaskList] = %@",[[TaskWallSystem sharedInstance] ChargeTaskList]);
    if ([[TaskWallSystem sharedInstance] ChargeTaskList] != nil && [TaskDictionary[@"ServiceTaskType"] intValue] == 1) {
        
        NSString *taskIdStr = [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"TaskId"];
        NSDictionary *param = [NSDictionary dictionaryWithObject:taskIdStr forKey:@"taskId"];
        
        __weak ViewController *weakSelf = self;
        [[TaskWallSystem sharedInstance] baseRequestWithParam:param requestURL:@"/requestLocation" succeededBlock:^(id responseObject) {
            
            __strong ViewController *strongSelf = weakSelf;
            [strongSelf LogStr:[NSString stringWithFormat:@"获取地区，code:%@",responseObject[@"code"]]];
            [strongSelf LogStr:[NSString stringWithFormat:@"获取地区，message:%@",responseObject[@"message"]]];
            
            if ([responseObject[@"code"] intValue] == 1) {
               
                NSMutableDictionary *changeDic = [NSMutableDictionary dictionaryWithDictionary:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"]];
                
                [changeDic setObject:responseObject[@"data"][@"Province"] forKey:@"Province"];
                [changeDic setObject:responseObject[@"data"][@"City"] forKey:@"City"];
                
                [[[TaskWallSystem sharedInstance] ChargeTaskList] setObject:changeDic forKey:@"data"];
                
                [[[TaskWallSystem sharedInstance] ChargeTaskList] writeToFile:TaskFile  atomically:NO];
                
//                NSString *provinceStr = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"Province"]];
//                NSString *cityStr = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"City"]];
//                strongSelf.AreaLabel.text = [NSString stringWithFormat:@"%@--%@",provinceStr, cityStr];
                
                [strongSelf refreshUIView];
            }
            
        } errorBlock:^(NSError *error) {
            
            [self LogStr:[NSString stringWithFormat:@"获取地区失败"]];
        }];
    }
    
}

- (IBAction)SwitchNewAccountWithAlert:(id)sender {
    
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要切换新账号吗？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self switchSwitchNewAccount];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"取消");
    }];
    
    [alertControl addAction:sureAction];
    [alertControl addAction:cancelAction];
    
    [self presentViewController:alertControl animated:YES completion:nil];
}

- (void)switchSwitchNewAccount {
    
    if ([[TaskWallSystem sharedInstance] ChargeTaskList] != nil) {
        
        NSDictionary *param = @{
                                @"service_daily_id":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"ServiceDailyId"],
                                @"taskId":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"TaskId"],
                                @"deviceId":[[TaskWallSystem sharedInstance] deviceId],//Iphone 6s
                                @"deviceString":[[TaskWallSystem sharedInstance] deviceString],
                                @"systemVersion":[[TaskWallSystem sharedInstance] systemVersion],
                                @"appVersion":[[TaskWallSystem sharedInstance] appVersion]
                                };
        __weak ViewController *weakSelf = self;
        [[TaskWallSystem sharedInstance] baseRequestWithParam:param requestURL:@"/requestTaskNewAccount" succeededBlock:^(id responseObject) {
            
            __strong ViewController *strongSelf = weakSelf;
            [strongSelf LogStr:[NSString stringWithFormat:@"切换新账号， code：%@", responseObject[@"code"]]];
            [strongSelf LogStr:[NSString stringWithFormat:@"切换新账号， message：%@", responseObject[@"message"]]];
            
            if ([responseObject[@"code"] intValue] == 1) {
                NSMutableDictionary *result = [NSMutableDictionary dictionary];
                [result addEntriesFromDictionary:responseObject];
                
                NSMutableDictionary *changeDic = [NSMutableDictionary dictionaryWithDictionary:[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"]];
                
                [changeDic setObject:result[@"data"][@"AccountFullName"] forKey:@"AccountFullName"];
                [changeDic setObject:result[@"data"][@"AccountName"] forKey:@"AccountName"];
                [changeDic setObject:result[@"data"][@"AccountPasswd"] forKey:@"AccountPasswd"];
                [changeDic setObject:result[@"data"][@"AccountIDcard"] forKey:@"AccountIDcard"];
                
                [[[TaskWallSystem sharedInstance] ChargeTaskList] setObject:changeDic forKey:@"data"];
                
                [[[TaskWallSystem sharedInstance] ChargeTaskList] writeToFile:TaskFile  atomically:NO];
                
                [self refreshUIView];
            }
        } errorBlock:^(NSError *error) {
            
            [self LogStr:[NSString stringWithFormat:@"账号切换失败"]];
            NSLog(@"切换新账号 error = %@",error);
        }];
    }
}


-(IBAction)chargeList:(id)sender
{
    [self LogStr:@"开始选取充值任务"];
    RechargeMainTableViewController *controller=[[RechargeMainTableViewController alloc] initWithNibName:@"RechargeMainTableViewController" bundle:nil];
    [self.navigationController pushViewController:controller animated:TRUE];
}
-(IBAction)starTask:(id)sender
{
    NSFileManager * fileManger = [NSFileManager defaultManager];
    if([[TaskWallSystem sharedInstance] SelectedTaskFromList]==nil){
        [self LogStr:@"没有选择任务，请在右下角打开任务选择界面"];
        
    }else if ([[TaskWallSystem sharedInstance] userId]==nil && [[TaskWallSystem sharedInstance] service_id]==nil) {
        [self LogStr:@"没有设置用户，请在右上角进行设置"];
    }else if ([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeNull){
        
        NSMutableDictionary *TaskDictionary = [[TaskWallSystem sharedInstance] SelectedTaskFromList];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:TaskDictionary[@"ServiceDailyId"] forKey:@"ServiceDailyId"];
        [param setValue:TaskDictionary[@"ServiceId"] forKey:@"ServiceId"];
        //1新增
        if ([TaskDictionary[@"ServiceTaskType"] intValue] == 1) {
            
            [self LogStr:[NSString stringWithFormat:@"请求新增任务%@",[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"GameInfo"][@"GameName"]]];
            
            [self getInfomationOfSelectedTaskWithRequestURL:@"/requestTaskNew" params:param taskType:1];
        }
        
        //2留存
        if ([TaskDictionary[@"ServiceTaskType"] intValue] == 2) {
            
            [self LogStr:[NSString stringWithFormat:@"请求留存任务%@",[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"GameInfo"][@"GameName"]]];
            
            [self getInfomationOfSelectedTaskWithRequestURL:@"/requestTaskActive" params:param taskType:2];
        }
        
        //4新增重做
        if ([TaskDictionary[@"ServiceTaskType"] intValue] == 4) {
            
            [self LogStr:[NSString stringWithFormat:@"请求新增重做任务%@",[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"GameInfo"][@"GameName"]]];
            
            [self getInfomationOfSelectedTaskWithRequestURL:@"/requestTaskNewRedo" params:param taskType:4];
        }
        
        //5留存重做
        if ([TaskDictionary[@"ServiceTaskType"] intValue] == 5) {
            
            [self LogStr:[NSString stringWithFormat:@"请求留存重做任务%@",[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"GameInfo"][@"GameName"]]];
            
            [self getInfomationOfSelectedTaskWithRequestURL:@"/requestTaskActiveRedo" params:param taskType:5];
        }
        
        //6新增练级
        if ([TaskDictionary[@"ServiceTaskType"] intValue] == 6) {
            
            [self LogStr:[NSString stringWithFormat:@"请求留存重做任务%@",[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"GameInfo"][@"GameName"]]];
            
            [self getInfomationOfSelectedTaskWithRequestURL:@"/requestTaskLevelingRedo" params:param taskType:6];
        }
        
    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==chareWaitInit){
        if([[TaskWallSystem sharedInstance] ChargeTaskList]==nil||[fileManger fileExistsAtPath:TaskFile isDirectory:false]==true){
            NSMutableDictionary * tempDictionary=[NSMutableDictionary dictionaryWithContentsOfFile:TaskFile];
            if(tempDictionary[@"ChargeHelperState"])
            {
                if([tempDictionary[@"ChargeHelperState"] integerValue]==1){
                    [self LogStr:@"任务正在初始化中,请确保脚本开启并调用"];
                }else if([tempDictionary[@"ChargeHelperState"] integerValue]==2){
                    [[TaskWallSystem sharedInstance] setRechargetQuestState:ChargeWaitInput];
                    [self LogStr:@"脚本初始化完成,等待用户手工上报数据"];
                }
            }else{
                [self LogStr:@"缓存数据异常"];
            }
            [self refreshUIView];
        }
    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeWaitInput){
        NSLog(@"%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"TaskDescriptionUrl"]);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString: [[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"TaskDescriptionUrl"]]];
    }else if ([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeWaitRequest){
        if([fileManger fileExistsAtPath:TaskFile isDirectory:false]==true){
            NSMutableDictionary * tempDictionary=[NSMutableDictionary dictionaryWithContentsOfFile:TaskFile];
            if(tempDictionary[@"ChargeHelperState"])
            {
                if([tempDictionary[@"ChargeHelperState"] integerValue]==3){
                    [self LogStr:@"等待脚本备份完成才能提交任务,请稍后调用"];
                }else if([tempDictionary[@"ChargeHelperState"] integerValue]==4){
                    [[TaskWallSystem sharedInstance] setRechargetQuestState:ChargeFinaRequst];
                    [self LogStr:@"脚本备份完成,请完成最终上传"];
                }
            }else{
                [self LogStr:@"缓存数据异常"];
            }
            [self refreshUIView];
        }
        
    }else if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeFinaRequst){
        dispatch_async(dispatch_queue_create("URLSuccess", NULL), ^{
            [[TaskWallSystem sharedInstance] commitTask:^(void) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([[TaskWallSystem sharedInstance] Commitresult][@"code"]){
                        [self LogStr:[NSString stringWithFormat:@"提交任务结果:%@",[[TaskWallSystem sharedInstance] Commitresult][@"code"]]];
                        [self LogStr:[NSString stringWithFormat:@"%@",[[TaskWallSystem sharedInstance] Commitresult][@"message"]]];
                        if([[[TaskWallSystem sharedInstance] Commitresult][@"code"] integerValue]==1){
                            [self LogStr:@"任务提交成功,清除任务缓存"];
                            [self cleanAll];
                        }
                    }
                });
            }];
        });
    }
    
}

-(IBAction)RecycleTask:(id)sender{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"任务"
                                                                   message:@"是否停止"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"停止" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                              [self.myTime invalidate];
                                                              self.myTime = nil;
                                                              
                                                              //响应事件
                                                              [self cleanAll];
                                                              NSLog(@"action = %@", action);
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", action);
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
-(IBAction)CommitBtnClicked:(id)sender{
    if([[TaskWallSystem sharedInstance] rechargetQuestState]==ChargeWaitInput){
        CommitTaskController *controller=[[CommitTaskController alloc] initWithNibName:@"CommitTaskController" bundle:nil];
        [self.navigationController pushViewController:controller animated:TRUE];
    }

}
-(void)cleanAll{
    [[TaskWallSystem sharedInstance] requestdeviceRecycle:^(void){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self LogStr:[NSString stringWithFormat:@"成功回收任务,请重新开始:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"message"]]];
            [[TaskWallSystem sharedInstance] setChargeTaskList:nil];
            [[TaskWallSystem sharedInstance] setRechargetQuestState:ChargeNull];
            [[TaskWallSystem sharedInstance] setSelectedTaskFromList:nil];
            [[TaskWallSystem sharedInstance] setCommitParamaList:nil];
            [self removeTaskChace];
            [self removeSelectedTaskChace];
            [self refreshUIView];
        });
    }];
    //nav为root UINavigationController
}

//TODO:获取验证码
- (void)getVerificationCode {
    static int funcUseNum = 0;
    static int timeNum = 0;
    
    funcUseNum ++;
    timeNum = timeNum + 5 ;
    NSLog(@"第 %d 此调用 获取验证码 方法",funcUseNum);
    NSLog(@"当前时间是 %d s",timeNum);
    
    if (funcUseNum >= 36) {
        
        [self.myTime invalidate];
        self.myTime = nil;
        
        funcUseNum = 0;
        
        [self LogStr:[NSString stringWithFormat:@"获取验证码失败！"]];
        
        return;
    }
    
    NSDictionary *params = @{
                             @"userId":[[TaskWallSystem sharedInstance] userId],
                             @"service_id":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"ServiceId"],
                             @"telnum":[[TaskWallSystem sharedInstance] ChargeTaskList][@"data"][@"Phone"]
                             };
    __weak ViewController *weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [[TaskWallSystem sharedInstance] requestUseGetWithParam:params requestURL:@"/getnews" succeededBlock:^(id responseObject) {
            
            __strong ViewController *strongSelf = weakSelf;
            
            [strongSelf LogStr:[NSString stringWithFormat:@"获取验证码， code：%@", responseObject[@"code"]]];
            [strongSelf LogStr:[NSString stringWithFormat:@"获取验证码， message：%@", responseObject[@"message"]]];
            
            if ([responseObject[@"code"] intValue] == 0) {
                
                [[TaskWallSystem sharedInstance] ChargeTaskList][@"VerCode"] = responseObject[@"data"][@"SmsContent"];
                
                [[[TaskWallSystem sharedInstance] ChargeTaskList] writeToFile:TaskFile atomically:YES];
                
                NSLog(@"[[TaskWallSystem sharedInstance] ChargeTaskList] = %@",[[TaskWallSystem sharedInstance] ChargeTaskList]);
                
                [strongSelf.myTime invalidate];
                strongSelf.myTime = nil;
                
                [strongSelf refreshUIView];
            }
        } errorBlock:^(NSError *error) {
            
            __strong ViewController *strongSelf = weakSelf;
            [strongSelf LogStr:[NSString stringWithFormat:@"获取验证码失败！"]];
        }];
    });
}

- (void)getInfomationOfSelectedTaskWithRequestURL:(NSString *)requestURL params:(NSMutableDictionary *)params taskType:(int)taskType {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[TaskWallSystem sharedInstance] requestSelectedTaskWithParam:params requestURL:requestURL taskType:taskType callback:^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self LogStr:[NSString stringWithFormat:@"code:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"code"]]];
                [self LogStr:[NSString stringWithFormat:@"message:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"message"]]];
                
                if([[[TaskWallSystem sharedInstance] ChargeTaskList][@"code"] intValue]==1)
                {
                    [[TaskWallSystem sharedInstance] setRechargetQuestState:chareWaitInit];
                    [self LogStr:@"任务初始化完成,请调用脚本完成环境恢复并再次刷新"];
                    [self refreshUIView];
                }
                if([[[TaskWallSystem sharedInstance] ChargeTaskList][@"code"] integerValue]==4){
                    OOLog(@"等待设备回收");
                    [[TaskWallSystem sharedInstance] requestdeviceRecycle:^(void){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            [self LogStr:[NSString stringWithFormat:@"成功回收任务,请重新开始:%@",[[TaskWallSystem sharedInstance] ChargeTaskList][@"message"]]];
                        });
                    }];
                }
            });
        }];
        
    });
}


//[fileManager removeItemAtPath:@"/var/mobile/Library/Safari/SuspendState.plist" error:nil];
//if([fileManger fileExistsAtPath:@"/safaricookies.tar.gz" isDirectory:false]==false){

//if ([[TaskWallSystem sharedInstance ]chargeQuestList]==nil) {
//    dispatch_async(dispatch_queue_create("URLSuccess", NULL), ^{
//        [[TaskWallSystem sharedInstance] requestServiceList:^(NSDictionary *dic) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                _data=[[TaskWallSystem sharedInstance] chargeQuestList];
//                [self.tableView reloadData];
//            });
//        }];
//    });
//}
@end
